"""分析数据控制器

处理数据分析相关的API接口
专注于分析结果数据的接收、存储和查询
原始脑波数据请使用 /eeg 接口
"""

from fastapi import APIRouter, Depends, HTTPException, Query
from typing import Optional, Dict, Any, List
from datetime import datetime
from loguru import logger

from app.config import settings
from app.services.analysis_service import AnalysisService
from app.schemas.analysis_schemas import AnalysisResultRequest

router = APIRouter(prefix="/analysis", tags=["数据分析"])

# 创建全局单例分析服务实例
_analysis_service_instance = None

def get_analysis_service() -> AnalysisService:
    """获取分析服务实例（单例模式）"""
    global _analysis_service_instance
    if _analysis_service_instance is None:
        _analysis_service_instance = AnalysisService()
        logger.info("创建分析服务单例实例")
    return _analysis_service_instance


@router.post("/data", summary="接收分析结果数据")
async def receive_analysis_data(
    request: AnalysisResultRequest,
    service: AnalysisService = Depends(get_analysis_service)
):
    """接收分析结果数据
    
    包括8频域数据比例、情绪状态等分析结果
    先存入内存，30秒后存入数据库
    
    Args:
        request: 分析结果请求
        service: 分析服务实例
        
    Returns:
        dict: 接收结果
    """
    try:
        print(request.data)
        result = service.receive_analysis_result(request)
        return result
        
    except ValueError as e:
        logger.warning(f"分析数据接收参数错误: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"分析数据接收失败: {str(e)}")
        raise HTTPException(status_code=500, detail="分析数据接收失败")





@router.get("/realtime/status", summary="实时状态查询")
async def get_realtime_status(
    room_ids: List[str] = Query(..., description="房间ID列表"),
    last_query_timestamp: float = Query(..., description="上次查询时间戳（Unix时间戳）"),
    service: AnalysisService = Depends(get_analysis_service)
):
    """实时状态查询接口
    
    根据房间ID列表和上次查询时间戳，返回按房间ID分类的状态数据
    每个房间的数据按时间戳排序形成列表，便于前端查询渲染
    
    Args:
        room_ids: 房间ID列表（必需）
        last_query_timestamp: 上次查询时间戳，Unix时间戳格式（必需）
        service: 分析服务实例
        
    Returns:
        dict: 按房间ID分类的状态数据，每个房间包含按时间戳排序的数据列表
    """
    try:
        result = await service.get_realtime_status_range(
            room_ids=room_ids,
            last_query_timestamp=last_query_timestamp
        )
        return {
            "status": "success",
            "message": "实时状态查询成功",
            "data": result
        }
        
    except ValueError as e:
        logger.warning(f"实时状态查询参数错误: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"实时状态查询失败: {str(e)}")
        raise HTTPException(status_code=500, detail="实时状态查询失败")


@router.get("/history", summary="获取分析结果历史记录")
async def get_analysis_history(
    session_id: Optional[str] = Query(None, description="会话ID"),
    room_id: Optional[str] = Query(None, description="房间ID"),
    user_id: Optional[str] = Query(None, description="用户ID"),
    start_time: Optional[str] = Query(None, description="开始时间"),
    end_time: Optional[str] = Query(None, description="结束时间"),
    limit: int = Query(settings.default_query_limit, description="返回记录数量限制"),
    service: AnalysisService = Depends(get_analysis_service)
):
    """获取分析结果历史记录
    
    从数据库中查询历史分析结果数据
    注意：此接口仅返回分析结果，原始脑波数据请使用 /eeg/history
    
    Args:
        session_id: 会话ID
        room_id: 房间ID
        user_id: 用户ID
        start_time: 开始时间
        end_time: 结束时间
        limit: 返回记录数量限制
        service: 分析服务实例
        
    Returns:
        dict: 分析结果历史记录数据
    """
    try:
        result = await service.get_analysis_history(
            session_id=session_id,
            room_id=room_id,
            user_id=user_id,
            start_time=start_time,
            end_time=end_time,
            limit=limit
        )
        return result
        
    except Exception as e:
        logger.error(f"获取分析历史记录失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取分析历史记录失败")